import tkinter as tk
from tkinter import ttk, messagebox
from pypinyin import pinyin, Style


def convert_to_pinyin():
    text = input_text.get("1.0", "end-1c")
    if not text.strip():
        messagebox.showwarning("警告", "请输入要转换的汉字")
        return

    try:
        # 带声调的拼音
        pinyin_tone = pinyin(text, style=Style.TONE)
        result_tone = " ".join([item[0] for item in pinyin_tone])

        # 不带声调的拼音
        pinyin_plain = pinyin(text, style=Style.NORMAL)
        result_plain = " ".join([item[0] for item in pinyin_plain])

        output_tone.delete(1.0, tk.END)
        output_tone.insert(tk.END, result_tone)

        output_plain.delete(1.0, tk.END)
        output_plain.insert(tk.END, result_plain)

    except Exception as e:
        messagebox.showerror("错误", f"转换失败: {str(e)}")


# 创建主窗口
root = tk.Tk()
root.title("汉字拼音转换器")
root.geometry("600x400")
root.configure(bg="#f0f0f0")

# 设置字体
font_style = ("Microsoft YaHei", 10)

# 创建界面组件
style = ttk.Style()
style.configure("TButton", font=font_style, padding=5)

frame = ttk.Frame(root, padding=20)
frame.pack(expand=True, fill=tk.BOTH)

input_label = ttk.Label(frame, text="输入汉字：", font=font_style)
input_label.grid(row=0, column=0, sticky=tk.W, pady=5)

input_text = tk.Text(frame, height=5, width=50, font=font_style,
                     wrap=tk.WORD, padx=5, pady=5)
input_text.grid(row=1, column=0, columnspan=2, pady=5)

convert_btn = ttk.Button(frame, text="转换拼音", command=convert_to_pinyin)
convert_btn.grid(row=2, column=0, columnspan=2, pady=10)

output_label1 = ttk.Label(frame, text="带声调拼音：", font=font_style)
output_label1.grid(row=3, column=0, sticky=tk.W, pady=5)

output_tone = tk.Text(frame, height=3, width=50, font=font_style,
                      padx=5, pady=5, state=tk.NORMAL)
output_tone.grid(row=4, column=0, columnspan=2, pady=5)

output_label2 = ttk.Label(frame, text="不带声调拼音：", font=font_style)
output_label2.grid(row=5, column=0, sticky=tk.W, pady=5)

output_plain = tk.Text(frame, height=3, width=50, font=font_style,
                       padx=5, pady=5, state=tk.NORMAL)
output_plain.grid(row=6, column=0, columnspan=2, pady=5)

# 设置组件样式
for widget in frame.winfo_children():
    if isinstance(widget, tk.Text):
        widget.configure(bg="white", relief=tk.FLAT,
                         highlightbackground="#cccccc", highlightthickness=1)
    elif isinstance(widget, ttk.Button):
        widget.configure(style="TButton")

root.mainloop()